/*
 * Copyright (C) 2017-2021
 * All rights reserved, Designed By 深圳中科鑫智科技有限公司
 * Copyright authorization contact 18814114118
 */
package com.shop.cereshop.business.controller;



import com.alibaba.fastjson.JSONObject;
import com.shop.cereshop.business.annotation.NoRepeatSubmit;
import com.shop.cereshop.business.annotation.NoRepeatWebLog;
import com.shop.cereshop.business.page.shop.Shop;
import com.shop.cereshop.business.param.shop.ShopParam;
import com.shop.cereshop.business.param.shop.ShopRechaargeParam;
import com.shop.cereshop.business.param.shop.ShopSaveParam;
import com.shop.cereshop.business.param.shop.ShopUpdateLogoParam;
import com.shop.cereshop.business.pay.weixin.service.WxPayService;
import com.shop.cereshop.business.pay.weixin.skd.HttpKit;
import com.shop.cereshop.business.pay.weixin.skd.PaymentKit;
import com.shop.cereshop.business.pay.weixin.skd.WXPayUtil;
import com.shop.cereshop.business.service.business.CerePlatformBusinessService;
import com.shop.cereshop.business.service.pay.CerePayLogService;
import com.shop.cereshop.business.service.shop.*;
import com.shop.cereshop.business.utils.ContextUtil;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.constant.IntegerEnum;
import com.shop.cereshop.commons.constant.StringEnum;
import com.shop.cereshop.commons.constant.WxPayEnum;
import com.shop.cereshop.commons.domain.business.CerePlatformBusiness;
import com.shop.cereshop.commons.domain.order.CereShopOrder;
import com.shop.cereshop.commons.domain.pay.CerePayLog;
import com.shop.cereshop.commons.domain.shop.*;
import com.shop.cereshop.commons.domain.shop.bo.CereShopRenewBo;
import com.shop.cereshop.commons.domain.shop.vo.ShopOrderStatVo;
import com.shop.cereshop.commons.domain.shop.vo.ShopPvVo;
import com.shop.cereshop.commons.domain.user.CerePlatformUser;
import com.shop.cereshop.commons.exception.CoBusinessException;
import com.shop.cereshop.commons.poi.ImportExeclUtil;
import com.shop.cereshop.commons.result.Result;
import com.shop.cereshop.commons.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.ContentHandler;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 店铺
 */
@RestController
@RequestMapping("shop")
/**
 * 注解方式生成日志对象，指定topic生成对象类名
 */
@Slf4j(topic = "ShopController")
@Api(value = "店铺模块", tags = "店铺模块")
public class ShopController {
    /**
     * 小程序appid
     */
    @Value("${weixin.appid}")
    private String appid;

    /**
     * 小程序秘钥
     */
    @Value("${weixin.secret}")
    private String secret;


    @Autowired
    private CerePlatformShopService cerePlatformShopService;

    @Autowired
    private CereShopReturnService cereShopReturnService;

    @Autowired
    private CereShopPersonalService cereShopPersonalService;

    @Autowired
    private CereShopIndividualBusinessesService cereShopIndividualBusinessesService;

    @Autowired
    private CereShopOtherOrganizationsService cereShopOtherOrganizationsService;

    @Autowired
    private CereShopEnterpriseService cereShopEnterpriseService;


    @Autowired
    private CerePlatformBusinessService cerePlatformBusinessService;


    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private CerePayLogService cerePayLogService;

    @Autowired
    private CereShopRenewService cereShopRenewService;

    /**
     * 商户秘钥
     */
    @Value("${weixin.key}")
    private String key;

    /**
     * 店铺二维码生成
     */
    @PostMapping(value = "/generateShopQR")
    @ApiOperation(value = "店铺二维码生成")
    public Result<String> generateShopQR() throws CoBusinessException{
        Long shopId = ContextUtil.getShopId();
        Shop shop = cerePlatformShopService.getById(shopId);
//        if (shop != null && shop.getShopQr() != null){
//            return new Result<String>(shop.getShopQr(),CoReturnFormat.SUCCESS);
//        }

        String accessToken = "";
        try {
            accessToken = QRCodeUtil.postToken(appid, secret);
        } catch (Exception e) {
            throw new CoBusinessException(CoReturnFormat.GENERATE_ACCESSTOKEN_FAIL);
        }
        String page = "pages/home/home?shopId=" + shopId;
        String encode = QRCodeUtil.geWeChatCode("shopId=" + shopId, page, accessToken);
        if (encode == null){
            throw new CoBusinessException(CoReturnFormat.GENERATE_QR_FAIL);
        }

//        byte[] data = FileUtil.getBytesByFile(filepath);
//        String encode = Base64Util.encode(data);
        if (shop.getShopQr() == null){
            CerePlatformShop platformShop = new CerePlatformShop();
            platformShop.setShopQr(encode);
            cerePlatformShopService.update(platformShop);
        }
        return new Result<String>(encode,CoReturnFormat.SUCCESS);
    }

    /**
     * 店铺充值续费
     */
    @PostMapping(value = "/recharge")
    @ApiOperation(value = "店铺充值续费")
    public Result< Map<String, String>> recharge(@RequestBody CereShopRenewBo param, HttpServletRequest request) throws CoBusinessException,Exception{
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        Long shopId = ContextUtil.getShopId();
        param.setShopId(shopId);
        param.setBusinessUserId(user.getBusinessUserId());
        CereShopRenew renew = new CereShopRenew();
        BeanUtils.copyProperties(param,renew);
        cereShopRenewService.save(renew);
        String body = "店铺充值续费";
        Map<String, String> prePayInfo = wxPayService.getPrePayInfo(renew.toString(),
                renew.getPayMoney(),
                null,
                WxPayEnum.PAY_TYPE_APP.getCode(),
                param.getOpenId(),
                body,
                IntegerEnum.WXPAY_TYPE_0.getCode());
        return new Result<>(prePayInfo,CoReturnFormat.SUCCESS);
    }

    /**
     * 店铺充值续费回调
     */
    @PostMapping(value = "/rechargeRolBack")
    @ApiOperation(value = "店铺充值续费回调")
    public void rechargeRolBack(HttpServletRequest request, HttpServletResponse response) throws CoBusinessException,Exception{
        log.info("进入微信小程序支付回调");
        String xmlMsg = HttpKit.readData(request);
        log.info("微信小程序通知信息"+xmlMsg);
        Map<String, String> resultMap = PaymentKit.xmlToMap(xmlMsg);
        log.info("resultMap"+resultMap);
        JSONObject result = new JSONObject();
        String outTradeNo = resultMap.get("out_trade_no");
        String[] split = outTradeNo.split("-");
        CereShopRenew renew  =cereShopRenewService.getById(split[0]);;
        if(!EmptyUtils.isEmpty(resultMap)){
            if(resultMap.get(StringEnum.WX_RETURN_CODE.getCode()).equals(StringEnum.WX_PAY_SUCCESS.getCode())){

                //验证签名
                if(WXPayUtil.isSignatureValid(resultMap,key)){
                    log.info("回调out_trade_no="+outTradeNo);
                    log.info("微信小程序支付回调成功");

                    if(!EmptyUtils.isEmpty(split)){
                        String renewId = split[0];
                        if(!EmptyUtils.isEmpty(renewId)){
                            //支付有礼
//                            cereShopOrderService.payGift(orderFormId);

                            CerePlatformShop shop = cerePlatformShopService.queryById(renew.getShopId());
                            shop.setEffectiveYear(shop.getEffectiveYear()+renew.getRenewYearNum());
                            cerePlatformShopService.updateById(shop);
                            result.put("code",200);
                            result.put("msg","支付成功");
                            result.put("data",renew.getShopRenewId());
                            PayWebSocketServer.sendInfo(result.toString(),renew.getBusinessUserId().toString());
                            //支付日志
                            CerePayLog cerePayLog = new CerePayLog();
                            cerePayLog.setShopId(renew.getShopId());
                            cerePayLog.setPaymentMode(renew.getPaymentMode());
                            cerePayLog.setState("0");
                            cerePayLog.setTransactionId(outTradeNo);
                            cerePayLog.setBusinessId(renew.getShopRenewId());
                            cerePayLog.setBusinessType(IntegerEnum.PAY_BUSINESS_TYPE_1.getCode());
                            cerePayLog.setTotalFee(renew.getPayMoney());
                            cerePayLogService.insert(cerePayLog);
                            //处理支付成功后的其他逻辑
//                            cereShopOrderService.handleWxLog(orderFormId,resultMap.get("transaction_id"),orderNo);
                        }

                    }
                }
            }else {
                result.put("code",9999);
                result.put("msg","支付失败");
                PayWebSocketServer.sendInfo(result.toString(),renew.getBusinessUserId().toString());
            }
        }else {

        }

        String result1 = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        response.getWriter().write(result1);
    }
    /**
     * 新建商家
     * @param param
     * @return
     */
    @PostMapping(value = "/save")
    @ApiOperation(value = "新建商家")
    public Result save(@RequestBody @Validated ShopSaveParam param, HttpServletRequest request) throws CoBusinessException{
        //校验商家名称是否存在
        CerePlatformShop shop=cerePlatformShopService.findByShopName(param.getShopName());
        if(shop!=null){
            return new Result(CoReturnFormat.SHOP_NAME_ALREADY);
        }
//        //校验手机号是否已注册
//        CerePlatformShop platformShop=cerePlatformShopService.findByPhone(param.getShopPhone());
//        if(platformShop!=null){
//            return new Result(CoReturnFormat.SHOP_PHONE_ALREADY);
//        }
        return new Result(cerePlatformShopService.save(param),CoReturnFormat.SUCCESS);
    }
    /**
     * 店铺信息查询
     * @param cerePlatformShop
     * @return
     */
    @PostMapping(value = "getById")
    @ApiOperation(value = "店铺信息查询")
    public Result<Shop> getById(@RequestBody ShopParam cerePlatformShop,HttpServletRequest request) throws CoBusinessException{
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        cerePlatformShop.setBusinessUserId(user.getBusinessUserId());
        cerePlatformShop.setShopId(ContextUtil.getShopId());
        Shop shop=cerePlatformShopService.getById(cerePlatformShop.getShopId());

//        if (IntegerEnum.UNTREATED.getCode().equals(shop.getCheckState())) {
//            return new Result(CoReturnFormat.SHOP_CHECK_STAY);
//        }
        return new Result(shop,CoReturnFormat.SUCCESS);
    }
    /**
     * 查询当前用户店铺

     * @return
     */
    @GetMapping(value = "queryList")
    @ApiOperation(value = "查询当前用户店铺")
    public Result<Shop> queryList(ShopParam param,HttpServletRequest request) throws CoBusinessException{
//        cerePlatformShop.setShopId(ContextUtil.getShopId());
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        param.setBusinessUserId(user.getBusinessUserId());
        return new Result(cerePlatformShopService.queryListByBusinessUserId(param.getBusinessUserId()),CoReturnFormat.SUCCESS);
    }

    /**
     * 当前用户切换店铺

     * @return
     */
    @GetMapping(value = "changeShops/{shopId}")
    @ApiOperation(value = "当前用户切换店铺")
    public Result<Shop> changeShop(@PathVariable("shopId")Long shopId,HttpServletRequest request) throws CoBusinessException{
//        cerePlatformShop.setShopId(ContextUtil.getShopId());
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        user.setActivateShopId(shopId);
        cerePlatformBusinessService.updateById(user);
        return new Result(1,CoReturnFormat.SUCCESS);
    }

    /**
     * 修改店铺信息
     * @param param
     * @return
     */
    @PostMapping(value = "update")
    @NoRepeatSubmit
    @ApiOperation(value = "修改店铺信息")
    @NoRepeatWebLog
    public Result updateLogo(@RequestBody ShopUpdateLogoParam param, HttpServletRequest request) throws CoBusinessException{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        param.setShopId(ContextUtil.getShopId());
        cerePlatformShopService.update(param,user);
        return new Result(user.getUsername(),"修改店铺信息", GsonUtil.objectToGson(param));
    }

    /**
     * 修改退货地址信息
     * @param cereShopReturn
     * @return
     */
    @PostMapping(value = "updateReturn")
    @NoRepeatSubmit
    @ApiOperation(value = "修改退货地址信息")
    @NoRepeatWebLog
    public Result updateReturn(@RequestBody CereShopReturn cereShopReturn, HttpServletRequest request) throws CoBusinessException{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        cereShopReturn.setShopId(ContextUtil.getShopId());
        cereShopReturnService.updateReturn(cereShopReturn,user);
        return new Result(user.getUsername(),"修改退货地址信息", GsonUtil.objectToGson(cereShopReturn));
    }

    /**
     * 店铺认证（个人）
     * @param personal
     * @return
     */
    @PostMapping(value = "personal")
    @NoRepeatSubmit
    @ApiOperation(value = "店铺认证（个人）")
    @NoRepeatWebLog
    public Result personal(@RequestBody CereShopPersonal personal, HttpServletRequest request) throws CoBusinessException{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        personal.setShopId(ContextUtil.getShopId());
        cereShopPersonalService.personal(personal,user);
        return new Result(user.getUsername(),"店铺认证（个人）", GsonUtil.objectToGson(personal));
    }

    /**
     * 店铺认证（个体工商户）
     * @param individualBusinesses
     * @return
     */
    @PostMapping(value = "individual")
    @NoRepeatSubmit
    @ApiOperation(value = "店铺认证（个体工商户）")
    @NoRepeatWebLog
    public Result individual(@RequestBody CereShopIndividualBusinesses individualBusinesses, HttpServletRequest request) throws CoBusinessException{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        individualBusinesses.setShopId(ContextUtil.getShopId());
        cereShopIndividualBusinessesService.individual(individualBusinesses,user);
        return new Result(user.getUsername(),"店铺认证（个体工商户）", GsonUtil.objectToGson(individualBusinesses));
    }

    /**
     * 店铺认证（企业）
     * @param enterprise
     * @return
     */
    @PostMapping(value = "enterprise")
    @NoRepeatSubmit
    @ApiOperation(value = "店铺认证（企业）")
    @NoRepeatWebLog
    public Result enterprise(@RequestBody CereShopEnterprise enterprise, HttpServletRequest request) throws CoBusinessException{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        enterprise.setShopId(ContextUtil.getShopId());
        cereShopEnterpriseService.enterprise(enterprise,user);
        return new Result(user.getUsername(),"店铺认证（企业）", GsonUtil.objectToGson(enterprise));
    }

    /**
     * 店铺认证（其他组织）
     * @param otherOrganizations
     * @return
     */
    @PostMapping(value = "organizations")
    @NoRepeatSubmit
    @ApiOperation(value = "店铺认证（其他组织）")
    @NoRepeatWebLog
    public Result organizations(@RequestBody CereShopOtherOrganizations otherOrganizations, HttpServletRequest request) throws CoBusinessException{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        otherOrganizations.setShopId(ContextUtil.getShopId());
        cereShopOtherOrganizationsService.organizations(otherOrganizations,user);
        return new Result(user.getUsername(),"店铺认证（其他组织）", GsonUtil.objectToGson(otherOrganizations));
    }

    /**
     * 修改店铺认证（个人）
     * @param personal
     * @return
     */
    @PostMapping(value = "updatePersonal")
    @NoRepeatSubmit
    @ApiOperation(value = "修改店铺认证（个人）")
    @NoRepeatWebLog
    public Result updatePersonal(@RequestBody CereShopPersonal personal, HttpServletRequest request) throws CoBusinessException{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        personal.setShopId(ContextUtil.getShopId());
        cereShopPersonalService.updatePersonal(personal,user);
        return new Result(user.getUsername(),"修改店铺认证（个人）", GsonUtil.objectToGson(personal));
    }

    /**
     * 修改店铺认证（个体工商户）
     * @param individualBusinesses
     * @return
     */
    @PostMapping(value = "updateIndividual")
    @NoRepeatSubmit
    @ApiOperation(value = "修改店铺认证（个体工商户）")
    @NoRepeatWebLog
    public Result updateIndividual(@RequestBody CereShopIndividualBusinesses individualBusinesses, HttpServletRequest request) throws CoBusinessException{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        individualBusinesses.setShopId(ContextUtil.getShopId());
        cereShopIndividualBusinessesService.updateIndividual(individualBusinesses,user);
        return new Result(user.getUsername(),"修改店铺认证（个体工商户）", GsonUtil.objectToGson(individualBusinesses));
    }

    /**
     * 修改店铺认证（企业）
     * @param enterprise
     * @return
     */
    @PostMapping(value = "updateEnterprise")
    @NoRepeatSubmit
    @ApiOperation(value = "修改店铺认证（企业）")
    @NoRepeatWebLog
    public Result updateEnterprise(@RequestBody CereShopEnterprise enterprise, HttpServletRequest request) throws CoBusinessException{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        enterprise.setShopId(ContextUtil.getShopId());
        cereShopEnterpriseService.updateEnterprise(enterprise,user);
        return new Result(user.getUsername(),"修改店铺认证（企业）", GsonUtil.objectToGson(enterprise));
    }

    /**
     * 修改店铺认证（其他组织）
     * @param otherOrganizations
     * @return
     */
    @PostMapping(value = "updateOrganizations")
    @NoRepeatSubmit
    @ApiOperation(value = "修改店铺认证（其他组织）")
    @NoRepeatWebLog
    public Result updateOrganizations(@RequestBody CereShopOtherOrganizations otherOrganizations, HttpServletRequest request) throws CoBusinessException{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        otherOrganizations.setShopId(ContextUtil.getShopId());
        cereShopOtherOrganizationsService.updateOrganizations(otherOrganizations,user);
        return new Result(user.getUsername(),"修改店铺认证（其他组织）", GsonUtil.objectToGson(otherOrganizations));
    }

    /**
     * 客户排行榜
     */
    @GetMapping(value = "buyerRankingList")
    @NoRepeatSubmit
    @ApiOperation(value = "客户排行榜")
    @NoRepeatWebLog
    public Result buyerRankingList(String startTime, String endTime,Integer sortType,HttpServletRequest request) throws CoBusinessException{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        Long shopId = ContextUtil.getShopId();

        return new Result(cerePlatformShopService.buyerRankingList(startTime,endTime,shopId,sortType),CoReturnFormat.SUCCESS);
    }

    /**
     * 店铺访问量统计
     */
    @GetMapping(value = "shopPv")
    @NoRepeatSubmit
    @ApiOperation(value = "店铺访问量统计")
    @NoRepeatWebLog
    public Result shopPv(String startTime, String endTime,HttpServletRequest request) throws CoBusinessException{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        Long shopId = ContextUtil.getShopId();
        List<ShopPvVo> shopPvVos = cerePlatformShopService.shopPv(startTime, endTime, shopId);
        Map<String, ShopPvVo> shopPvMap = new HashMap<>();
        for (ShopPvVo shopPvVo : shopPvVos) {
            shopPvMap.put(shopPvVo.getDay(),shopPvVo);
        }
        List<String> days = DateUtil.traverseDate(startTime, endTime);
        shopPvVos = new ArrayList<>();
        for (String day : days) {
            ShopPvVo shopPvVo = shopPvMap.get(day);
            if (shopPvVo == null){
                shopPvVo = new ShopPvVo();
                shopPvVo.setBuyerUserNum(0l);
                shopPvVo.setVisitCount(0l);
                shopPvVo.setDay(day);
                shopPvVo.setShopId(shopId);
            }
            shopPvVos.add(shopPvVo);
        }
        return new Result(shopPvVos,CoReturnFormat.SUCCESS);
    }
    /**
     * 店铺
     */
    @GetMapping(value = "shopOrderStat")
    @NoRepeatSubmit
    @ApiOperation(value = "店铺订单统计")
    @NoRepeatWebLog
    public Result shopOrderStat(String startTime, String endTime,HttpServletRequest request) throws CoBusinessException{
        //获取当前登录账户
        CerePlatformBusiness user = (CerePlatformBusiness) request.getAttribute("user");
        Long shopId = ContextUtil.getShopId();
        List<ShopOrderStatVo> shopOrderStatVos = cerePlatformShopService.shopOrderStat(startTime, endTime, shopId);
        Map<String, ShopOrderStatVo> shopOrderStatVoMap = new HashMap<>();
        for (ShopOrderStatVo shopOrderStatVo : shopOrderStatVos) {
            shopOrderStatVoMap.put(shopOrderStatVo.getDay(),shopOrderStatVo);
        }
        List<String> days = DateUtil.traverseDate(startTime, endTime);
        shopOrderStatVos = new ArrayList<>();
        for (String day : days) {
            ShopOrderStatVo shopOrderStatVo = shopOrderStatVoMap.get(day);
            if (shopOrderStatVo == null){
                shopOrderStatVo = new ShopOrderStatVo();
                shopOrderStatVo.setOrderPriceTotal(0l);
                shopOrderStatVo.setOrderCount(0l);
                shopOrderStatVo.setDay(day);
                shopOrderStatVo.setShopId(shopId);
            }
            shopOrderStatVos.add(shopOrderStatVo);
        }
        return new Result(shopOrderStatVos,CoReturnFormat.SUCCESS);
    }
}
